#    tribalgrowth is a growth monitor for the online game Tribal Wars.
#    Copyright 2009 Nathan Michaels                                            
#                                                                              
#    This file is part of tribalgrowth.                                        
#                                                                              
#    tribalgrowth is free software: you can redistribute it and/or modify      
#    it under the terms of the GNU General Public License as published by      
#    the Free Software Foundation, either version 2 of the License, or         
#    (at your option) any later version.                                       
#                                                                              
#    tribalgrowth is distributed in the hope that it will be useful,           
#    but WITHOUT ANY WARRANTY; without even the implied warranty of            
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             
#    GNU General Public License for more details.                              
#                                                                              
#    You should have received a copy of the GNU General Public License         
#    along with tribalgrowth.  If not, see <http://www.gnu.org/licenses/>. 

import urllib
import gzip
import StringIO

DEBUG = False # Debug mode uses STATS_FILE locally. No network.

#STATS_BASE_URL = 'http://uk2.tribalwars.co.uk/map/'
# This world is nice and small:
STATS_BASE_URL = 'http://classic.tribalwars.net/map/'
STATS_FILE = 'village.txt.gz'
STATS_URL =  STATS_BASE_URL + STATS_FILE

# To start with, we'll just grab a particular dataset and return it as a file
# like object.

def download (url):
    opener = urllib.URLopener ()
    f = opener.open (url)
    s = StringIO.StringIO (f.read())
    return s

def pretend (url):
    f = open (STATS_FILE)
    return f

if DEBUG:
    download = pretend

def grab ():
    gzipped = download (STATS_URL) # This will be improved for multiple servers.
    text = gzip.GzipFile (STATS_FILE, fileobj = gzipped).read()
    return text

def dictify (text):
    listed = text.split('\n')
    out = []
    for row in listed:
        # $id, $name, $x, $y, $player, $points, $rank
        if not row:
            continue
        ID, name, x, y, player, points, rank = row.split(',')
        dicted = dict (id=ID, name=name, x=x, y=y, player=player, points=points,
                       rank=rank)
        out.append (dicted)
    return out

def get_dict ():
    t = grab ()
    return dictify (t)

if __name__=='__main__':
    t = grab ()
    print t
